package com.abc.pro.ui.phone.fragment;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.client.methods.HttpGet;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.util.Pair;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import com.abc.pro.api.HttpGetTask;
import com.abc.pro.api.HttpGetTask.HttpTaskHandler;
import com.abc.pro.api.OddsParser;
import com.abc.pro.model.Event;
import com.abc.pro.model.GroupEvents;
import com.abc.pro.model.OddsEarlyEvent;
import com.abc.pro.model.OddsInplayEvent;
import com.abc.pro.model.OddsTodayEvent;
import com.abc.pro.widget.PopupView;
import com.abc.pro186.App;
import com.abc.pro186.AppData;
import com.abc.pro186.AppData.URL;
import com.abc.pro186.BaseApplication;
import com.abc.pro186.OddAdapter;
import com.abc.pro186.OddListView;
import com.abc.pro186.R;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragment;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;

public class OddFragment extends SherlockFragment implements OnClickListener{
    private final int ACTION_MENU_REFRESH 	= 1000;
    private final int ACTION_MENU_VIEW 		= 1001;
    private final int ACTION_MENU_SORT 		= 1002;

    private OddListView lstvMain;

    private PopupView mPopupViewSorting;
    private PopupView mPopupViewViewing;
    private Context currentContext;
    private String mUrlCur = URL.ODDsEARLY;
    private LinearLayout mlvLoading;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.currentContext = getActivity();
        SherlockFragmentActivity activity = getSherlockActivity();
        if (activity != null) {
            ActionBar actionbar = activity.getSupportActionBar();
            /*if (actionbar != null) {
                Context context = actionbar.getThemedContext();
                // Inflate the custom view
                View customNav = LayoutInflater.from(context).inflate(R.layout.custom_menu_wcsc_close_the_salses, null);

                Button btnSave = (Button) customNav.findViewById(R.id.btn_save);
                btnSave.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                    }
                });

                // Attach to the action bar
                actionbar.setCustomView(customNav, new LayoutParams(-1, -1));
                actionbar.setDisplayShowCustomEnabled(true);                
            }*/
        }

        setHasOptionsMenu(true);

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        // return super.onCreateView(inflater, container, savedInstanceState);
        ViewGroup rootView = (ViewGroup)inflater.inflate(R.layout.odd_layout, container,false);

        //todo change to use OddListView
        lstvMain = (OddListView) rootView.findViewById(R.id.lstvMain);
        lstvMain.setPinnedHeaderView(LayoutInflater.from(getActivity()).inflate(R.layout.odd_list_section_header, lstvMain, false));
        //		List<Pair<String, List<Object>>> all = new ArrayList<Pair<String,List<Object>>>();
        //		for(int i = 0; i < 5; i++){
        //			all.add(new Pair<String, List<Object>>("Champion League " + i, dummyArray()));
        //		}
        //		
        //		OddAdapter adapter = new OddAdapter(all, getActivity());
        //		lstvMain.setAdapter(adapter);

        initPopupViews(lstvMain);
        mlvLoading = (LinearLayout) rootView.findViewById(R.id.ll_loading_panel);
        
        showLoading(true);
        getData(AppData.SORT_DATE, AppData.TIMEZONE_DEFAULT, 0);
        return rootView;
    }
    
    private void showLoading(boolean isShow){
        mlvLoading.setVisibility(isShow?View.VISIBLE:View.GONE);
    }
    
    private void initPopupViews(View anchorView) {
        if (anchorView == null) {
            return;
        }
        LayoutInflater inflator = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        ViewGroup soringViewGroup = (ViewGroup) inflator.inflate(R.layout.popup_view_odd_sorting, null);

        mPopupViewSorting = new PopupView(anchorView);
        mPopupViewSorting.setContentView(soringViewGroup);
        soringViewGroup.findViewById(R.id.sortingbutton1).setOnClickListener(this);
        soringViewGroup.findViewById(R.id.sortingbutton2).setOnClickListener(this);

        ViewGroup viewingViewGroup = (ViewGroup) inflator.inflate(R.layout.popup_view_odd_viewing, null);
        mPopupViewViewing = new PopupView(anchorView);
        mPopupViewViewing.setContentView(viewingViewGroup);
        viewingViewGroup.findViewById(R.id.button1).setOnClickListener(this);
        viewingViewGroup.findViewById(R.id.button2).setOnClickListener(this);
        viewingViewGroup.findViewById(R.id.button3).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
        case R.id.sortingbutton1:
            getData(AppData.SORT_MATCH, AppData.TIMEZONE_DEFAULT, 0);
            reloadData(AppData.SORT_MATCH, mPopupViewSorting);
            break;
        case R.id.sortingbutton2:
            reloadData(AppData.SORT_DATE, mPopupViewSorting);
            break;
        case R.id.button1:
            mUrlCur = URL.ODDsINPLAY;
            reloadData(AppData.SORT_DATE, mPopupViewViewing);
            break;
        case R.id.button2:
            mUrlCur = URL.ODDsTODAY;
            reloadData(AppData.SORT_DATE, mPopupViewViewing);
            break;
        case R.id.button3:
            mUrlCur = URL.ODDsEARLY;
            reloadData(AppData.SORT_DATE, mPopupViewViewing);
            break;
        default:
            break;
        }
    }
    
    private void reloadData(int sort, PopupView popupIsShow){
        showLoading(true);
        getData(sort, AppData.TIMEZONE_DEFAULT, 0);
        if(popupIsShow != null){
            popupIsShow.dismiss();
        }
    }
    
    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.add(0, ACTION_MENU_SORT, 0, "")
        .setIcon(R.drawable.ic_action_sort_by_size)
        .setShowAsAction(
                MenuItem.SHOW_AS_ACTION_IF_ROOM
                | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        menu.add(0, ACTION_MENU_VIEW, 1, "")
        .setIcon(R.drawable.ic_action_menu_view)
        .setShowAsAction(
                MenuItem.SHOW_AS_ACTION_IF_ROOM
                | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        menu.add(0, ACTION_MENU_REFRESH, 2, "")
        .setIcon(R.drawable.ic_action_menu_refresh)
        .setShowAsAction(
                MenuItem.SHOW_AS_ACTION_IF_ROOM
                | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
        // super.onCreateOptionsMenu(menu, inflater);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // return super.onOptionsItemSelected(item);
        if (item == null) {
            return super.onOptionsItemSelected(item);
        }		
        switch (item.getItemId()) {
        /*case android.R.id.home:
			toggle();
			break;*/

        case ACTION_MENU_REFRESH:
            BaseApplication.makeToastMsg("get data from PRO186");
            reloadData(0, null);
            // getData(AppData.SORT_MATCH, AppData.TIMEZONE_DEFAULT, 0);
            break;

        case ACTION_MENU_VIEW:
            // BaseApplication.makeToastMsg("Cháº¿ Ä‘á»™ xem: \nTrong tráº­n - HÃ´m nay - Dá»± Ä‘oÃ¡n sá»›m");
            if (mPopupViewViewing != null) {
                mPopupViewViewing.show();
            }
            break;

        case ACTION_MENU_SORT:
            // BaseApplication.makeToastMsg("Sáº¯p sáº¿p bá»Ÿi: \nGiáº£i Ä‘áº¥u - Thá»�i gian");
            if (mPopupViewSorting != null) {
                mPopupViewSorting.show();
            }
            break;

        }
        return true;
    }

    protected List<Object> dummyArray() {
        ArrayList<Object> arr = new ArrayList<Object>();
        int rand = 8;//new Random().nextInt(6);
        for (int i = 0; i < rand; i++){
            arr.add("object" + i);
        }
        return arr;
    }

    // TODO get data from PRO186 server
    private void getData(int sort, int timezone, int page_no){
        HttpGetTask httpTask = new HttpGetTask();
        httpTask.setTaskHandler(new HttpTaskHandler() {
            @Override
            public void taskSuccessful(JSONObject json) {
                try {
                    OddAdapter adapter = null;
                    lstvMain.setAdapter(adapter);
                    if(TextUtils.equals(mUrlCur, URL.ODDsINPLAY)){
                        GroupEvents<OddsInplayEvent> odds = OddsParser.parseImplayJson(json);
                        adapter = new OddAdapter(odds.prepareData(), currentContext);
                    } else if(TextUtils.equals(mUrlCur, URL.ODDsEARLY)){
                        GroupEvents<OddsEarlyEvent> odds = OddsParser.parseEarlyJson(json);
                        adapter = new OddAdapter(odds.prepareData(), currentContext);
                    }else{
                        GroupEvents<OddsTodayEvent> odds = OddsParser.parseTodayJson(json);
                        adapter = new OddAdapter(odds.prepareData(), currentContext);
                    }
                    
                    lstvMain.setAdapter(adapter);
                } catch (JSONException e) {
                    Log.e(">>>", "parser getData() parser json response failed");
                }
                
                showLoading(false);
            }

            @Override
            public void taskFailed() {
                BaseApplication.makeToastMsg("Không lấy được thông tin từ PRO186");
                showLoading(false);
            }
        });

        String params = getParams(sort, timezone, page_no);
        httpTask.execute(new HttpGet(mUrlCur + params));
    }
    
    private int mCurrSort = AppData.SORT_DATE;
    private String getParams(int sort, int timezone, int page_no){
        // String params = String.format(AppData.PARAMS, AppData.SORT_DATE, AppData.TIMEZONE_DEFAULT, 0);
        if(sort != 0) mCurrSort = sort;
        return String.format(AppData.PARAMS, mCurrSort, timezone, page_no);
    }


}
